import requests
import json
from pprint import pprint

from vcpedia.fetch_page_by_id import get_final_content as fetch_page_content_by_id

#最初有记录的时间：2025-03-26T00:00:00Z
def fetch_mediawiki_changes(rcstart,rcend):
    api_url = "https://vcpedia.cn/api.php"
    all_changes = []
    continue_params = {}
    
    while True:
        params = {
            "action": "query",
            "list": "recentchanges",
            "rcstart": rcstart,
            "rcend": rcend,
            "rctype": "edit|new",
            "rcprop": "title|ids|timestamp",
            "rclimit": 5,  # 增加每页限制
            "format": "json",
            "rcdir": "newer",
            "rctoponly": 1
        }
        
        # 添加继续参数（如果有）
        params.update(continue_params)
        
        try:
            response = requests.get(api_url, params=params, timeout=15)
            response.raise_for_status()
            data = response.json()
            
            if 'error' in data:
                print(f"API错误: {data['error']['info']}")
                break
            
            
            # 添加当前页结果
            page_changes = data.get("query", {}).get("recentchanges", [])
            all_changes.extend(page_changes)
            
            print(f"已获取 {len(page_changes)} 条记录，总计 {len(all_changes)} 条")
            


            # 检查是否有更多结果
            if 'continue' in data:
                continue_params = data['continue']
            else:
                print(f"所有数据获取完成! 总计 {len(all_changes)} 条记录")
                break
                
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {str(e)}")
            break
            
    return all_changes
# 执行函数
if __name__ == "__main__":
    result = fetch_mediawiki_changes("2025-03-29T00:00:00Z","2025-04-01T00:00:00Z")
    #pprint(result)
    for change in result:
        pageid = change.get("pageid")
        title, content, final_pageid, error=fetch_page_content_by_id(pageid)
        if error:
            print(f"错误: {error}")
        else:
            print(f"最终pageid: {final_pageid}")
            print(f"标题: {title}")
            print(f"内容: {content}")
            
        break
